/*!
 * \file jxbankagree_core.h
 *
 * \brief JXBANKAGREE模块主文件
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2017/04/20
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <frct_detect_hash.h>

#include "frlog.h"
#include "frreport_comm.h"

#include "frct_comm.h"

#include "config.h"
#include "jxbankagree_comm.h"
#include "jxbankagree_header.h"
#include "jxbankagree_packet.h"
#include "jxbankagree_message.h"

extern void *g_p_apm_context;

/*******************************************************************************
*  FUNC     :  jxbankagree Session初始化
*  ARGS     :  *p_st_session                            (L7层session信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __jxbankagree_private_session_init(L7_session *p_st_session)
{
    JXBANKAGREE_PRINT_INFO("session init\n");
    L7session_jxbankagree_private *p_st_jxbankagree_private = NULL;
    L7session_jxbankagree *p_st_jxbankagree_sess = NULL;
    L7_jxbankagree_packet *p_st_jxbankagree_packet = NULL;

    // 1. 初始化jxbankagree的私有session信息
    if ((p_st_jxbankagree_sess = (L7session_jxbankagree *) frmalloc(sizeof(L7session_jxbankagree))) == NULL)
    {
        JXBANKAGREE_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_jxbankagree_sess, 0x00, sizeof(L7session_jxbankagree));

    // 2. 初始化jxbankagree格式的packet包
    if ((p_st_jxbankagree_packet = (L7_jxbankagree_packet *) frmalloc(sizeof(L7_jxbankagree_packet))) == NULL)
    {
        JXBANKAGREE_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_jxbankagree_packet, 0x00, sizeof(L7_jxbankagree_packet));
    if (jxbankagree_init_packet(p_st_jxbankagree_packet) != FR_SUCC)
        goto error;

    // 3. 创建和初始化jxbankagree的私有信息
    if ((p_st_jxbankagree_private = (L7session_jxbankagree_private *) frmalloc(sizeof(L7session_jxbankagree_private))) == NULL)
    {
        JXBANKAGREE_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_jxbankagree_private, 0x00, sizeof(L7session_jxbankagree_private));
    p_st_jxbankagree_private->p_st_sess = p_st_jxbankagree_sess;
    p_st_jxbankagree_private->p_st_jxbankagree_packet = p_st_jxbankagree_packet;
    p_st_jxbankagree_private->p_st_session = p_st_session;

    // 4. 设置L7_session的p_session_private信息
    frct_set_session_private(p_st_session, (void *)p_st_jxbankagree_private);

    return FR_SUCC;
error:
    if (p_st_jxbankagree_packet != NULL)
    {
        bytebuff_free(&(p_st_jxbankagree_packet->p_st_packet));
        jxbankagree_free((void **) &p_st_jxbankagree_packet);
    }
    jxbankagree_free((void **) &p_st_jxbankagree_private);
    return FR_FAIL;
}

FR_STATIC void __jxbankagree_destroy_session(L7session_jxbankagree **pp_st_session)
{
    if (pp_st_session == NULL || *pp_st_session == NULL)
        return;

    jxbankagree_free((void **) pp_st_session);
    return;
}

FR_STATIC int __jxbankagree_analyze_direct(char *p_payload
                                    , unsigned int ui_payload_len)
{
    // 请求报文头包含Version字段
    if (memcmp(p_payload + 8, "\x20\x20", 2) != 0)
        return FR_DIRECT_CLIENT2SRV;
    else
        return FR_DIRECT_SRV2CLIENT;
}

int jxbankagree_detect(Conntrack *p_st_conn
                , Apm_packet *p_analyze_in)
{
    JXBANKAGREE_PRINT_INFO("jxbankagree_detect...\n");
    int i_analyzed_direct = 0;

#if APM_JXBANKAGREE_DBG
    char arr_ip_src[56], arr_ip_dst[56];
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->dst_ip));
    JXBANKAGREE_PRINT_TIMEVAL("PacketIn", p_analyze_in->st_timestamp);
    JXBANKAGREE_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] Length:[%u]\n", arr_ip_src, p_analyze_in->src_port, arr_ip_dst, p_analyze_in->dst_port, p_analyze_in->ui_payload_len);
#endif

    if (jxbankagree_header_detect(p_analyze_in->p_payload, p_analyze_in->ui_payload_len) != APM_L7_IS_YES)
        goto unknown;

    if (p_analyze_in->i_direction == FR_DIRECT_UNKNOWN || frct_get_direct_known(p_st_conn) == FR_DIRECT_UNKNOWN)
    {
        i_analyzed_direct = __jxbankagree_analyze_direct(p_analyze_in->p_payload, p_analyze_in->ui_payload_len);
        if (i_analyzed_direct == FR_DIRECT_CLIENT2SRV)
        {
            JXBANKAGREE_PRINT_CRIT("Set Server:[%s:%d]\n", arr_ip_dst, p_analyze_in->dst_port);
            if (frcap_set_cs_srv(p_st_conn, p_analyze_in->dst_ip, p_analyze_in->dst_port) != FR_SUCC)
                goto unknown;
        }
        else if (i_analyzed_direct == FR_DIRECT_SRV2CLIENT)
        {
            JXBANKAGREE_PRINT_CRIT("Set Server:[%s:%d]\n", arr_ip_src, p_analyze_in->src_port);
            if (frcap_set_cs_srv(p_st_conn, p_analyze_in->src_ip, p_analyze_in->src_port) != FR_SUCC)
                goto unknown;
        }
        else
        {
            JXBANKAGREE_PRINT_EMERG("Can not analyze direction\n\n");
            goto unknown;
        }
    }

    JXBANKAGREE_PRINT_INFO("jxbankagree_detect success\n\n");
    return APM_L7_IS_YES;
unknown:
    JXBANKAGREE_PRINT_INFO("jxbankagree_detect failed\n\n");
    return APM_L7_IS_UNKNOWN;
}

int jxbankagree_analyze(Conntrack *p_st_conn
                , Apm_packet *p_analyze_in
                , Frhash_header *p_st_hash_report)
{
    JXBANKAGREE_PRINT_INFO("jxbankagree_analyze\n");
    L7_session *p_st_session = NULL;
    L7session_jxbankagree_private *p_st_session_private = NULL;
    L7_jxbankagree_packet *p_st_jxbankagree_packet = NULL;
    int i_unfragmented_ret = 0;
    int i_analyze_ret = APM_L7_ANALYZE_SUCC;                  // 本函数的返回值
    char arr_ip_src[56], arr_ip_dst[56];
    L7session_jxbankagree *p_st_sess = NULL;
    int i_analyzed_direct = 0;
    Frreport_body_data *p_st_body = NULL;

    if (p_st_conn == NULL || p_analyze_in == NULL
      || p_st_hash_report == NULL)
        return APM_L7_ANALYZE_FAIL;

    p_st_session = frct_get_session(p_st_conn);
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->dst_ip));

    JXBANKAGREE_PRINT_TIMEVAL("PacketIn", p_analyze_in->st_timestamp);
    JXBANKAGREE_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] SessionID:[%s]\n", arr_ip_src, p_analyze_in->src_port, arr_ip_dst, p_analyze_in->dst_port, p_st_session->arr_session_id);

    /*
    * 如果入力p_st_packet是FIN包, 说明本次connection结束,
    * 释放本次session信息. 如果入力p_st_packet是SYN包,说明新的
    * connection开始了, 释放上次可能残留的session信息
    */
    if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_FIN || p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_SYN)
    {
        if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_SYN)
            JXBANKAGREE_PRINT_INFO("SYN PACKET\n");
        else if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_FIN)
            JXBANKAGREE_PRINT_INFO("FIN PACKET\n");

        if ((p_st_session_private = (L7session_jxbankagree_private *) frct_get_session_private(p_st_session)) != NULL)
        {
            jxbankagree_session_destory(p_st_session->p_session_private);
            p_st_session->p_session_private = NULL;
        }
        JXBANKAGREE_PRINT("### i_analyze_ret:[%d]\n\n", i_analyze_ret);
        return i_analyze_ret;
    }

    // 本次链路的第一个有效packet包,创建链路
    if (p_st_session->p_session_private == NULL)
    {
        // 初始化te的session数据
        if (__jxbankagree_private_session_init(p_st_session) != FR_SUCC)
            goto jxbankagree_analyze_fail;

        // 设置session uuid
        fruuid(p_st_session->arr_session_id);
    }

    if (p_analyze_in->i_direction == FR_DIRECT_UNKNOWN || frct_get_direct_known(p_st_conn) == FR_DIRECT_UNKNOWN)
    {
        i_analyzed_direct = __jxbankagree_analyze_direct(p_analyze_in->p_payload, p_analyze_in->ui_payload_len);
        if (i_analyzed_direct == FR_DIRECT_CLIENT2SRV)
        {
            JXBANKAGREE_PRINT_CRIT("Set Server:[%s:%d]\n", arr_ip_dst, p_analyze_in->dst_port);
            if (frcap_set_cs_srv(p_st_conn, p_analyze_in->dst_ip, p_analyze_in->dst_port) != FR_SUCC)
                goto jxbankagree_analyze_fail;
        }
        else if (i_analyzed_direct == FR_DIRECT_SRV2CLIENT)
        {
            JXBANKAGREE_PRINT_CRIT("Set Server:[%s:%d]\n", arr_ip_src, p_analyze_in->src_port);
            if (frcap_set_cs_srv(p_st_conn, p_analyze_in->src_ip, p_analyze_in->src_port) != FR_SUCC)
                goto jxbankagree_analyze_fail;
        }
        else
        {
            JXBANKAGREE_PRINT_EMERG("Can not analyze direction\n\n");
            goto jxbankagree_analyze_fail;
        }

        p_analyze_in->i_direction = i_analyzed_direct;
    }

    // 打印方向
    switch (p_analyze_in->i_direction)
    {
        case FR_DIRECT_CLIENT2SRV:
            JXBANKAGREE_PRINT("client["KLIMEGREEN"%s:%d"RESET"] to server["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] ->>>>>>>>>>>>>>>>>>>>>>>\n",
                      arr_ip_src,
                      p_analyze_in->src_port,
                      arr_ip_dst,
                      p_analyze_in->dst_port,
                      p_analyze_in->ui_payload_len);
            break;
        case FR_DIRECT_SRV2CLIENT:
            JXBANKAGREE_PRINT("server["KLIMEGREEN"%s:%d"RESET"] to client["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] <<<<<<<<<<<<<<<<<<<<<<<-\n",
                      arr_ip_src,
                      p_analyze_in->src_port,
                      arr_ip_dst,
                      p_analyze_in->dst_port,
                      p_analyze_in->ui_payload_len);
            break;
        default:
            JXBANKAGREE_PRINT("unknown direction, src["KLIMEGREEN"%s:%d"RESET"], dest["KLIMEGREEN"%s:%d"RESET"]\n",
                      arr_ip_src,
                      p_analyze_in->src_port,
                      arr_ip_dst,
                      p_analyze_in->dst_port);
            goto jxbankagree_analyze_fail;
    }

    p_st_session_private = (L7session_jxbankagree_private *) frct_get_session_private(p_st_session);
    p_st_sess = p_st_session_private->p_st_sess;
    p_st_jxbankagree_packet = p_st_session_private->p_st_jxbankagree_packet;

    i_unfragmented_ret = jxbankagree_packet_unfragment(p_st_sess, p_analyze_in, p_st_jxbankagree_packet);
    if (i_unfragmented_ret == APM_JXBANKAGREE_CHECK_FRAGMENT_NEED_NEXT_PACKET)
        goto jxbankagree_analyze_todo;
    else if (i_unfragmented_ret == APM_JXBANKAGREE_CHECK_FRAGMENT_ERROR)
        goto jxbankagree_analyze_fail;
    else if (i_unfragmented_ret == APM_JXBANKAGREE_CHECK_FRAGMENT_SKIP)
        goto jxbankagree_analyze_success;

    if (p_analyze_in->i_direction == FR_DIRECT_CLIENT2SRV)
    {
        if (jxbankagree_req(p_st_conn, p_st_sess, p_st_jxbankagree_packet, p_st_hash_report) == FR_SUCC)
        {
            i_analyze_ret = APM_L7_ANALYZE_SET_REQ(APM_L7_ANALYZE_SUCC);
            goto jxbankagree_analyze_success;
        }
    }
    else
    {
        if (jxbankagree_resp(p_st_conn, p_st_sess, p_st_jxbankagree_packet, p_st_hash_report) == FR_SUCC)
        {
            i_analyze_ret = APM_L7_ANALYZE_SET_RESP(APM_L7_ANALYZE_SUCC);
            goto jxbankagree_analyze_success;
        }
    }

jxbankagree_analyze_success:
    JXBANKAGREE_PRINT("### i_analyze_ret success:[%d]\n\n", i_analyze_ret);
    return i_analyze_ret;

jxbankagree_analyze_todo:
    JXBANKAGREE_PRINT("### i_analyze_ret todo:[%d]\n\n", APM_L7_ANALYZE_TODO);
    return APM_L7_ANALYZE_TODO;

jxbankagree_analyze_fail:
    frreport_body_free(&p_st_body);
    if (jxbankagree_packet_is_in_fragment(p_st_jxbankagree_packet))
    {
        if (bytebuff_setPosition(p_st_jxbankagree_packet->p_st_packet, 0) != FR_SUCC)
        {
            p_st_jxbankagree_packet->fragment_state = APM_JXBANKAGREE_FRAGMENT_INIT;
            return APM_L7_ANALYZE_FAIL;
        }
        goto jxbankagree_analyze_todo;
    }
    else
    {
        JXBANKAGREE_PRINT_PACKET("error packet", p_st_jxbankagree_packet);
        jxbankagree_init_packet(p_st_jxbankagree_packet);
    }

    JXBANKAGREE_PRINT_EMERG("### i_analyze_ret fail:[%d]\n\n", APM_L7_ANALYZE_FAIL);
    return APM_L7_ANALYZE_FAIL;
}

/*******************************************************************************
*  FUNC     :  释放 L7_jxbankagree_packet
*  ARGS     :  **pp_st_jxbankagree_packet              (L7_jxbankagree_packet)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __jxbankagree_destroy_packet(L7_jxbankagree_packet **pp_st_jxbankagree_packet)
{
    if (pp_st_jxbankagree_packet == NULL || *pp_st_jxbankagree_packet == NULL)
        return;

    L7_jxbankagree_packet *p_st_jxbankagree_packet = *pp_st_jxbankagree_packet;
    bytebuff_free(&(p_st_jxbankagree_packet->p_st_packet));
    jxbankagree_free((void **) pp_st_jxbankagree_packet);
    return;
}

int jxbankagree_session_destory(void *p_st_session_privajxbankagree_in)
{
    JXBANKAGREE_PRINT(KBLUE "\njxbankagree_session_destory run\n" RESET);
    if (p_st_session_privajxbankagree_in == NULL)
        return FR_SUCC;

    L7session_jxbankagree_private *p_st_private = (L7session_jxbankagree_private *) p_st_session_privajxbankagree_in;

    __jxbankagree_destroy_session(&(p_st_private->p_st_sess));

    __jxbankagree_destroy_packet(&(p_st_private->p_st_jxbankagree_packet));

    frreport_body_l7list_free(&(p_st_private->p_report_comm));
    frreport_body_l7list_free(&(p_st_private->p_report_req));

    jxbankagree_free((void **) &p_st_private);

    JXBANKAGREE_PRINT_INFO("leave jxbankagree_session_destory\n");
    return FR_SUCC;
}
